package com.sgcc.lms.openstack.util;

import com.sgcc.lms.openstack.enumeration.StatusCode;
import com.sgcc.lms.openstack.exception.*;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * @Author: 李孟帅
 * @CreateTime: 2020-07-21 17:52
 * @Description:
 */
public class RestClientUtil {
    /**
     * @Author 李孟帅
     * @Description 执行http请求
     * @Date 2020/7/20
     **/
    public static String execute(HttpRequestBase httpRequestBase) throws IOException, HttpException {
        //创建http客户端
        HttpClient httpClient = HttpClientBuilder.create().build();
        //发送get请求
        HttpResponse response = httpClient.execute(httpRequestBase);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == StatusCode.NOT_CONTENT.getCode()) {
            return "ok";
        }
        //获取响应
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity);
        if (statusCode == StatusCode.BAD_REQUEST.getCode()) {
            throw new BadRequestException(result,statusCode);
        } else if (statusCode == StatusCode.UNAUTHORIZED.getCode()) {
            throw new UnauthorizedException(result,statusCode);
        } else if (statusCode == StatusCode.FORBIDDEN.getCode()) {
            throw new ForbiddenException(result,statusCode);
        } else if (statusCode == StatusCode.NOT_FOUND.getCode()) {
            throw new NotFoundException(result,statusCode);
        } else if (statusCode == StatusCode.CONFLICT.getCode()) {
            throw new ConflictException(result,statusCode);
        }
        return result;
    }
}
